﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VDataAdapter.EventManagement;

namespace VDataAdapter.TestData
{
    class TransactionsEventData
    {        
        public TransactionsEvent[] Transactions;
        public Queue<string> StrMsgs;
    }

    /// <summary>
    /// This class read data from file which was written by PSAdapterThreadCapturer
    /// Provide way to read file such as
    /// FirstTimeEvent.test
    /// Transactions.test etc
    /// </summary>
    class PSATCapturerDataReader
    {
        public static TransactionsEventData LoadTransactionEvent(string filepath)
        {
            Object[] list = PriceServerObjectFile.LoadFromFile(filepath);
            var transactionList = new List<TransactionsEvent>();
            var strMsgs = new Queue<string>();

            if (list.Length == 0)
                throw new FormatException("PSATCapturerDataReader: File does not contain any object");

            if (!IsValidTransactionFileFormat(list))
                throw new FormatException("PSATCapturerDataReader: File format is incorrect for Transactions event data");

            foreach (Object obj in list)
            {
                if (obj.GetType().Equals(typeof(TransactionsEvent)))
                {
                    transactionList.Add((TransactionsEvent)obj);
                }

                if (obj.GetType().Equals(typeof(Queue<string>)))
                {
                    strMsgs = (Queue<string>)obj;
                }
            }

            var data = new TransactionsEventData();
            data.Transactions = transactionList.ToArray();
            data.StrMsgs = strMsgs;

            return data;
        }

        private static bool IsValidTransactionFileFormat(Object[] objs)
        {
            if (!HasQueueStringAsLastElement(objs)) return false;

            // all previous element must be TransactionEvent
            for (int i = 0; i < objs.Length - 1; i++)
            {
                if (objs[i].GetType() != typeof(TransactionsEvent))
                    return false;
            }

            return true;
        }

        /// <summary>
        /// This method can be used for all file format
        /// since all event are recorded with their Queue<string> in the last element
        /// </summary>
        /// <param name="objs"></param>
        /// <returns></returns>
        private static bool HasQueueStringAsLastElement(Object[] objs)
        {
            if (objs[objs.Length - 1].GetType() != typeof(Queue<string>))
                return false;
            return true;
        }


        
    }
}
